<template>
  <div class="case-type-container">
    <el-card class="case-type-card">
      <template #header>
        <div class="card-header">
          <h3>案件类型管理</h3>
          <el-button type="primary" @click="handleAdd">新增案件类型</el-button>
        </div>
      </template>

      <el-form :model="queryForm" :inline="true" @submit.prevent="handleQuery">
        <el-form-item label="类型名称">
          <el-input v-model="queryForm.name" placeholder="请输入类型名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 使用树形表格展示案由数据 -->
      <el-table
        :data="caseTypeList"
        border
        stripe
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="案由名称" min-width="200" />
        <el-table-column prop="description" label="描述" min-width="250" />
        <el-table-column prop="create_time" label="创建时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryForm.page"
        v-model:page-size="queryForm.limit"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useLawcaseStore } from '../../store/lawcase'

  // 定义案件类型接口
  interface CaseType {
    id: number
    name: string
    description: string
    create_time: string
    // 树形结构支持
    children?: CaseType[]
  }

  // 数据列表
  const caseTypeList = ref<CaseType[]>([])
  const loading = ref(false)
  const total = ref(0)

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    name: '',
  })

  // 对话框
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)

  // 表单数据
  const form = reactive({
    id: 0,
    name: '',
    description: '',
  })

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
  }

  // 表单引用
  const formRef = ref()

  // 创建store实例
  const lawcaseStore = useLawcaseStore()

  // 获取数据列表
  const getCaseTypeList = async () => {
    loading.value = true
    try {
      // 调用真实API
      const res = await lawcaseStore.getCaseCauseListAction(queryForm)

      if (res.code === 0) {
        // 保持树形结构并格式化数据
        const formatTreeNode = (node: any): CaseType => {
          return {
            id: node.id,
            name: node.name,
            description: node.description || '',
            create_time: node.create_time
              ? new Date(node.create_time * 1000).toLocaleString('zh-CN')
              : '',
            children: node.children
              ? node.children.map((child: any) => formatTreeNode(child))
              : undefined,
          }
        }

        // 直接使用树形数据
        caseTypeList.value = res.data.map((item: any) => formatTreeNode(item))
        // 由于是树形结构，总数可能不准确，这里保持原有的统计方式
        total.value = res.count || 0 || 0
      } else {
        ElMessage.error(res.msg || '获取案由列表失败')
      }
    } catch (error) {
      console.error('获取案由列表失败:', error)
      ElMessage.error('获取案由列表失败')
    } finally {
      loading.value = false
    }
  }

  // 查询
  const handleQuery = () => {
    queryForm.page = 1
    getCaseTypeList()
  }

  // 重置
  const handleReset = () => {
    queryForm.name = ''
    queryForm.page = 1
    getCaseTypeList()
  }

  // 分页
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    getCaseTypeList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    getCaseTypeList()
  }

  // 新增
  const handleAdd = () => {
    dialogTitle.value = '新增案件类型'
    isEdit.value = false
    Object.assign(form, {
      id: 0,
      name: '',
      description: '',
    })
    dialogVisible.value = true
  }

  // 编辑
  const handleEdit = (row: any) => {
    dialogTitle.value = '编辑案件类型'
    isEdit.value = true
    Object.assign(form, row)
    dialogVisible.value = true
  }

  // 删除
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确定要删除该案件类型吗？', '提示', {
      type: 'warning',
    })
      .then(async () => {
        try {
          // await api.deleteCaseType(row.id)
          ElMessage.success('删除成功')
          getCaseTypeList()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {})
  }

  // 提交表单
  const handleSubmit = () => {
    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          if (isEdit.value) {
            // await api.updateCaseType(form)
          } else {
            // await api.addCaseType(form)
          }
          ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          getCaseTypeList()
        } catch (error) {
          ElMessage.error(isEdit.value ? '编辑失败' : '新增失败')
        }
      }
    })
  }

  // 初始化
  onMounted(() => {
    getCaseTypeList()
  })
</script>

<style scoped>
  .case-type-container {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .case-type-card {
    margin-bottom: 20px;
  }
</style>
